<template>
  <div>
    <page-table
      rowKey="userDeptId"
      ref="userDeptPageTable"
      query-type="list"
      :query-api="userDept_queryListApi"
      :delete-api="userDept_deletesApi"
      :query-param="queryParam"
      :columns="columns"
      @addClick="addClick"
    >
      <template #customMain="{text,record}">
        <a-switch v-model="record.main" @change="updateUserDept(record)" />
      </template>
      <template #customValid="{text,record}">
        <a-switch v-model="record.valid" @change="updateUserDept(record)" />
      </template>
      <template #customTimeEnd="{text,record}">
        <a-date-picker
          style="width:160px"
          v-model="record.timeEnd"
          valueFormat="YYYY-MM-DD"
          @change="updateUserDept(record)"
        />
      </template>
    </page-table>
    <a-modal title="选择部门" :visible="visible" @ok="addUserUnit" @cancel="()=>{visible=false}">
      <unit-tree
        v-if="visible"
        :edit-tree="false"
        :checkable="true"
        :disableCheckbox="disableCheckbox"
        ref="unitTree"
      />
    </a-modal>
  </div>
</template>

<script>
import {
  userDept_queryListApi,
  userDept_deletesApi,
  userDeptUpdate,
  userDeptInsertBatch
} from "@/api/org/userDept";
import UnitTree from "@/views/org/user/component/unitTree";
const columns = [
  { title: "部门", dataIndex: "unitName" },
  {
    title: "主要部门",
    dataIndex: "main",
    scopedSlots: { customRender: "customMain" }
  },
  {
    title: "是否有效",
    dataIndex: "valid",
    scopedSlots: { customRender: "customValid" }
  },
  {
    title: "失效时间",
    dataIndex: "timeEnd",
    width: "200px",
    scopedSlots: { customRender: "customTimeEnd" }
  }
];
export default {
  components: { UnitTree },
  props: {
    userId: String
  },
  data() {
    return {
      columns,
      userDept_queryListApi,
      userDept_deletesApi,
      queryParam: {
        userId: this.userId
      },
      visible: false,
      disableCheckbox: []
    };
  },
  methods: {
    reload() {
      this.$refs.userDeptPageTable.reload();
    },
    updateUserDept(record, extData) {
      userDeptUpdate(record, extData).then(response => {
        this.reload();
      });
    },
    addClick() {
      //获得当前用户的所有部门信息
      let unitArray = this.$refs.userDeptPageTable.getDataSource();
      this.disableCheckbox = []; //清理之前存在的禁用值
      unitArray.forEach(item => {
        this.disableCheckbox.push(item.deptId);
      });
      this.visible = true;
    },
    addUserUnit() {
      let checkedKeys = this.$refs.unitTree.checkedKeys;
      if (checkedKeys.length == 0) {
        this.$message.warning("请选择部门");
        return false;
      }
      let userDepts = [];
      for (let i in checkedKeys) {
        userDepts.push({ userId: this.userId, deptId: checkedKeys[i] });
      }
      userDeptInsertBatch(userDepts).then(response => {
        this.visible = false;
        this.reload();
      });
    }
  }
};
</script>